let isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

if ('serviceWorker' in navigator) {
  // 注册Service Workder, 用于缓存管理
  navigator.serviceWorker
    .register('./sw.js')
    .then(function (reg) {
      window.isSupportPWA = false
      console.log('UmMeeting Service Worker Registered:' + reg.scope)
      let appPromptEvent = null
      const installBtn = document.getElementById('installBtn')
      if (installBtn) {
        window.addEventListener('beforeinstallprompt', function (event) {
          console.log('触发事件：beforeinstallprompt')
          window.isSupportPWA = true
          event.preventDefault()
          appPromptEvent = event
          if (localStorage.getItem('promptPwa') === null || localStorage.getItem('promptPwa') === 'NaN' || localStorage.getItem('promptPwa') === true) {
            document.getElementsByClassName('downloadPWA')[0].style.display = 'block'
          }
          return false
        })
        installBtn.addEventListener('click', function () {
          if (!window.isSupportPWA) {
            let msg = '当前浏览器不支持，请使用其他浏览器进行尝试！'
            if (isIOS) msg = 'iOS设备不支持该功能！'
            alert(msg)
            return
          }
          document.getElementsByClassName('downloadPWA')[0].style.display = 'none'
          if (appPromptEvent !== null) {
            console.log(appPromptEvent)
            appPromptEvent.prompt()
            appPromptEvent.userChoice.then(function (result) {
              if (result.outcome === 'accepted') {
                console.log('同意安装应用')
              } else {
                console.log('不同意安装应用')
              }
              appPromptEvent = null
            })
          }
        })
        window.addEventListener('appinstalled', function (event) {
          console.log('应用已安装')
          document.getElementsByClassName('downloadPWA')[0].style.display = 'none'
        })
        // updatefound is fired if service-worker.js changes.
        reg.onupdatefound = function () {
          // The updatefound event implies that reg.installing is set; see
          // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
          var installingWorker = reg.installing

          installingWorker.onstatechange = function () {
            switch (installingWorker.state) {
              case 'installed':
                if (navigator.serviceWorker.controller) {
                  // At this point, the old content will have been purged and the fresh content will
                  // have been added to the cache.
                  // It's the perfect time to display a "New content is available; please refresh."
                  // message in the page's interface.
                  console.log('New or updated content is available.')
                } else {
                  // At this point, everything has been precached.
                  // It's the perfect time to display a "Content is cached for offline use." message.
                  console.log('Content is now available offline!')
                }
                break

              case 'redundant':
                console.error('The installing service worker became redundant.')
                break
            }
          }
        }
      }
    })
    .catch(function (e) {
      console.error('Error during service worker registration:', e)
    })

  // 做一个简单get请求客户端，用于请求缓存版本，进行版本管理
  // var HttpClient = function () {
  //   this.get = function (aUrl, aCallback) {
  //     var anHttpRequest = new XMLHttpRequest()
  //     anHttpRequest.onreadystatechange = function () {
  //       if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200) {
  //         aCallback(anHttpRequest.responseText)
  //       }
  //     }

  //     anHttpRequest.open('GET', aUrl, true)
  //     anHttpRequest.send(null)
  //   }
  // }

  // 缓存管理的策略：
  // 1. 获取当前版本号
  // 2. 如果本地有版本号且版本号低于获取到的版本号，就清空缓存重新刷新一下页面
  // 3. 保存当前版本号到localStorage内
  // var client = new HttpClient()
  // client.get('./version.txt', function (response) {
  //   var localVersion = window.localStorage.getItem('cache_version')
  //   var needClearCache = localVersion && Number(localVersion) < Number(response)
  //   window.localStorage.setItem('cache_version', response)
  //   // console.log('服务器缓存版本号:', response, '本地缓存版本号：', localVersion, '是否需要清理缓存：', needClearCache)
  //   if (needClearCache) {
  //     // 清理缓存，并重载页面
  //     caches.keys().then((keyList) => {
  //       return Promise.all(keyList.map((key) => {
  //         // if (cacheName !== key) {
  //         // Service Workder更新后，清空缓存
  //         console.log('SW: delete', key)
  //         return caches.delete(key)
  //         // }
  //       }))
  //     })
  //     // TODO: 修改为更好的清理缓存方法
  //     window.location.reload(true)
  //   }
  // })
}